package com.kang.mavenweb.action;

import com.alibaba.fastjson.JSONObject;

import com.kang.mavenweb.domain.User;
import com.kang.mavenweb.service.ILoginService;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.util.List;


@ParentPackage ("struts-default")
public class LoginAction extends ActionSupport {

    @Autowired
    private ILoginService loginService;

    private String username;
    private String password;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Action(value = "login")
    public String login() throws IOException {
        User user = new User ( );
        user.setUsername (username);
        user.setPassword (password);
        List<User> login = loginService.login (user);
        if(login.size ()==0){
            ServletActionContext.getResponse ().getWriter ().write (JSONObject.toJSONString ("0"));
        }else{
            //登录成功,存储用户信息到session中
            ServletActionContext.getRequest ().getSession ().setAttribute ("user", login.get (0));
            ServletActionContext.getResponse ().getWriter ().write (JSONObject.toJSONString ("1"));
        }
        return null;
    }

}
